#
#  QCPySightAppDelegate.py
#  QCPySight
#

from Foundation import *
from AppKit import *

import Quartz
import debug
import time
from imageTool import *

from PyObjCTools import NibClassBuilder

class QCPySightAppDelegate(NibClassBuilder.AutoBaseClass):
    def init(self):
        self = super(QCPySightAppDelegate, self).init()
        if not self:
            return None
        self._observeApp()
        return self
                
    def _observeApp(self):    
        NSNotificationCenter.defaultCenter().\
                             addObserver_selector_name_object_(self,
                                  "applicationWillTerminate:",
                                  NSApplicationWillTerminateNotification,
                                  None)
        NSNotificationCenter.defaultCenter().\
                             addObserver_selector_name_object_(self,
                                  "applicationDidFinishLaunching:",
                                  NSApplicationWillTerminateNotification,
                                  None)

    def _observePatchController(self):
        """This starts observing value changes on the output"""
        self.patchController.addObserver_forKeyPath_options_context_(self, u"patch.outputImage.value", 0, 0)
        
    def observeValueForKeyPath_ofObject_change_context_(self, keyPath, object, change, context):
        #if keyPath == u"patch.outputImage.value":
        self._handleImageChange(object.valueForKeyPath_(keyPath))
        
    def _handleImageChange(self, image):
        NSLog(imageToolPlugIn.imageAverage_(image))
        #gets us the average pixel value of the image
                                  
    def applicationWillTerminate_(self, notification):
        """Cleanup here"""
        self.patchController.removeObserver_forKeyPath_(self, u"patch.outputImage.value")
        NSNotificationCenter.defaultCenter().removeObserver_(self)
    
    def applicationDidFinishLaunching_(self, notification):
        self._observePatchController()
        
    def log_(self, sender):
        NSLog(dir(self.patchController.patch()))
        NSLog(type(self.patchController.patch()))
        time.sleep(2)